/** 
  考核模板设置
*/
<template>
  <div class="template-setting-container">
    <condition-card @reset="reset" @search="onSubmit" label-position="right" label-width="150px">
      <el-row :gutter="24" style="height: 50px;">
        <el-col :span="8">
          <el-form-item :label="$t('templateSetting.templateName')">
            <el-input v-model="queryForm.condition.templateName" clearable :maxlength="64" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('templateSetting.baseLevel')">
            <el-select v-model="baseLevel" multiple clearable style="width: 100%">
              <el-option
                v-for="item in options.baseLevel"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('templateSetting.isEnabled')">
            <el-select v-model="queryForm.condition.isEnabled" clearable style="width: 100%">
              <el-option
                v-for="item in options.isEnabled"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </condition-card>
    <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
      <h1 class="condition-title">{{$t('templateSetting.templateNameSettingList')}}</h1>
      <div class="edu-opertion-bar sub-title">
        <div class="float-right" style="display: flex;">
          <el-button v-if="permitToExport" type="primary" @click="exportTemplate">{{$t('common.btn.export')}}</el-button>
          <el-button v-if="permitToAdd" type="primary" @click="addTemplate">{{$t('common.btn.add')}}</el-button>
        </div>
      </div>
      <edu-table :pagination="false" :order='false' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
        <edu-table-column :label="$t('templateSetting.templateName')" prop="templateName"></edu-table-column>
        <edu-table-column :label="$t('templateSetting.description')" prop="description"></edu-table-column>
        <edu-table-column :label="$t('templateSetting.baseLevel')" prop="baseLevel">
          <template slot-scope="scope">
            {{ scope.row.baseLevel | baseLevel }}  
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('templateSetting.isEnabled')">
          <template slot-scope="scope">
            <div class="is-enabled-container">
              <el-button v-if="scope.row.isEnabled === 0" type="danger" plain>{{ scope.row.isEnabled | isEnabled }}</el-button>
              <el-button v-else type="success" plain>{{ scope.row.isEnabled | isEnabled }}</el-button>
            </div>
          </template>   
        </edu-table-column>
        <edu-table-column :label="$t('common.text.operation')" fit width="200">
          <template slot-scope="scope">
            <el-button v-if="permitToEdit" type="text" @click="editAssessIndex(scope.row)">{{$t('common.btn.edit')}}</el-button>
            <el-button v-if="permitToDetail" type="text" @click="selectAssessIndex(scope.row)">{{$t('graduateBase.details')}}</el-button>
            <el-button v-if="permitToSelectTable" type="text" @click="selectAssessIndexTable(scope.row)">{{$t('templateSetting.selectAssessIndexTable')}}</el-button>
          </template>
        </edu-table-column>
      </edu-table>
      <el-row type="flex" class="row-bg" justify="end">
        <el-col>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryForm.pageNum_"
            :page-sizes="[20, 40, 80, 100]"
            :page-size="queryForm.pageSize_"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryForm.total_"
            style="float:right;margin-top:10px"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog
      :before-close="beforeClose"
      :title="title"
      width="50%"
      class="template-setting-dialog"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="dialogForm" label-position="right" ref="dialogForm" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="$t('templateSetting.templateName') + ':'"
              prop="templateName"
              :rules="[{ required: true, message: $t('templateSetting.requireTemplateName'), trigger: 'blur' }, { validator: checkSpecial, trigger: 'blur'}]">
              <el-input :disabled="dialogMode === 'details'" :placeholder="$t('common.pla.pleaseInput')" v-model="dialogForm.templateName" :maxlength="64" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item 
              :label="$t('templateSetting.baseLevel') + ':'"
              prop="baseLevel"
              :rules="[{ required: true, message: $t('templateSetting.requireBaseLevel'), trigger: 'change'}]">
              <el-select :disabled="dialogMode === 'details'" v-model="dialogForm.baseLevel" :placeholder="$t('common.pla.pleaseSelect')" clearable>
                <el-option
                  v-for="item in options.baseLevel"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item 
              :label="$t('templateSetting.isEnabled') + ':'"
              prop="isEnabled"
              :rules="[{ required: true, message: $t('templateSetting.requireIsEnabled'), trigger: 'change'}]">
              <el-select :disabled="dialogMode === 'details'" v-model="dialogForm.isEnabled" :placeholder="$t('common.pla.pleaseSelect')" clearable>
                <el-option
                  v-for="item in options.isEnabled"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('templateSetting.description') + ':'" prop="description" :rules="[{ validator: checkSpecial, trigger: 'blur'}]">
              <el-input
                :disabled="dialogMode === 'details'"
                type="textarea"
                :rows="5"
                :maxlength="512"
                :placeholder="$t('common.pla.pleaseInput')"
                v-model="dialogForm.description">
              </el-input>
            </el-form-item>
          </el-col >
        </el-row>
      </el-form>
      <el-dialog
        width="25%"
        ref="innerDialog"
        :title="$t('graduateBase.prompt')"
        :visible.sync="innerVisible"
        append-to-body
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :top="'28vh'">
        <div style="text-align: left;margin-bottom: 25px;">{{$t('graduateBase.cancelTip')}}</div>
        <div style="text-align: right;">
          <el-button type="primary" @click="confirmInner('innerDialog')">{{$t('common.btn.confirm')}}</el-button>
          <el-button @click="cancelInner('innerDialog')">{{$t('common.btn.cancel')}}</el-button>
          <el-button type="primary" @click="confirmAndClose('dialogForm')">{{$t('graduateBase.saveAndClose')}}</el-button>
        </div>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <template v-if="dialogMode === 'add' || dialogMode === 'edit'">
          <el-button @click="cancel('dialogForm')">{{$t('common.btn.cancel')}}</el-button>
          <el-button type="primary" @click="save('dialogForm')">{{$t('common.btn.save')}}</el-button>
        </template>
        <template v-else-if="dialogMode === 'details'">
          <el-button @click="closeDialog('dialogForm')">{{$t('common.btn.close')}}</el-button>
        </template>
      </span>
    </el-dialog>
    <el-dialog
      @close="dataListProp={}"
      :title="$t('templateSetting.assessIndexTable')"
      width="80%"
      :visible.sync="tableFlag">
      <assess-index-table  
        :dataListProp="dataListProp"  
        :showFlag="tableFlag"
        @close="(flag) => { tableFlag = flag }">
      </assess-index-table>
    </el-dialog>
    <edu-export-dialog
      :disabled="exportButton"
      :title="$t('message.prompt')"
      ref="downloadRef"
      :data="exportResult">
    </edu-export-dialog>
  </div>
</template>
<script>
import assessIndexTable from './assessIndexTable';
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent';
export default {
  components: {
    'assess-index-table': assessIndexTable
  },
  data () {
    return {
      auths: [],
      permitToExport: false,
      permitToAdd: false,
      permitToEdit: false,
      permitToDetail: false,
      permitToSelectTable: false,
      title: '',
      dialogVisible: false,
      innerVisible: false,
      tableFlag: false,
      multipleSelection: [],
      baseLevel: [],
      queryForm: {
        pageNum_: 1,
        pageSize_: 20,
        total_: 0,
        condition: {
          templateName: '',
          baseLevel: '',
          isEnabled: ''
        }
      },
      dataListProp: {},
      dialogMode: 'add',
      options: {
        // 实习基地级别
        baseLevel: [
          {
            label: '校级',
            value: '1'
          },
          {
            label: '院级',
            value: '2'
          }
        ],
        // 启停状态
        isEnabled: [
          {
            label: '停用',
            value: 0
          },
          {
            label: '启用',
            value: 1
          }
        ]
      },
      dialogForm: {
        templateName: '',
        baseLevel: '',
        isEnabled: '',
        description: ''
      },
      editModeInfo: {},
      dataList: [],
      exportButton: false,
      exportResult: null
    }
  },
  filters: {
    isEnabled(val) {
      switch (val) {
        case 0:
          return '停用'
        case 1:
          return '启用'
        default:
          return val
      }
    },
    baseLevel(val) {
      switch (val) {
        case '1':
          return '校级'
        case '2':
          return '院级'
        default:
          return val
      }
    }
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths;
      }
    }
    graduateStudentApi.assessmentTempSetList(this.queryForm).then(res => {
      this.dataList = res.data.list;
      this.queryForm.total_ = res.data.total_;
    });
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im;
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback();
      }
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1;
      this.getListData();
    },
    // 轮询直到获取key值的接口返回
    cycleToGetKey() {
      setTimeout(() => {
        let currentIds = [];
        if (this.multipleSelection.length > 0) {
          this.multipleSelection.forEach((element) => {
            currentIds.push(element.id);
          });
        }
        graduateStudentApi.exportAssessTemp({
          "templateName": this.queryForm.condition.templateName,
          "baseLevel": this.queryForm.condition.baseLevel,
          "isEnabled": this.queryForm.condition.isEnabled,
          "selectRowIds": currentIds
        }).then(res => {
          if (res.success) {
            this.$refs.downloadRef.close();
            this.exportButton = false;
            this.normalDelayRequest(res.key, res.msg);
          } else {
            this.cycleToGetKey();
          }
        });
      }, 3000);
    },
    // 导出异步
    delayRequest(key, name) {
      setTimeout(() => {
        graduateStudentApi.downloadGetKey(key, name).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/practiceservice/export/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // Normal导出异步
    normalDelayRequest(key, name) {
      setTimeout(() => {
        graduateStudentApi.downloadGetKey(key).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/practiceservice/export/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // 导出模板
    exportTemplate() {
      // 1、第一步：调该接口，获取key值以及msg中的文件名
      // 2、第二步：将key值放入接口传参
      // 3、第三步：传入path值以及name(msg中的文件名)值，下载文件
      this.exportResult = null;
      this.$refs.downloadRef.open();
      this.exportButton = true;
      this.cycleToGetKey();
    },
    // 新增模板
    addTemplate() {
      this.title = this.$t('templateSetting.addAssessTempSet');
      this.dialogMode = 'add';
      this.dialogVisible = true;
    },
    // 编辑模板
    editAssessIndex(row) {
      this.title = this.$t('templateSetting.editAssessTempSet');
      this.dialogMode = 'edit';
      this.editModeInfo = JSON.parse(JSON.stringify(row));
      let currentRow = JSON.parse(JSON.stringify(row));
      this.dialogForm = currentRow;
      this.dialogForm['oldTemplateName'] = row.templateName;
      this.dialogVisible = true;
    },
    // 查看模板详情
    selectAssessIndex(row) {
      this.title = this.$t('templateSetting.selectAssessTempSet');
      this.dialogMode = 'details';
      let currentRow = JSON.parse(JSON.stringify(row));
      this.dialogForm = currentRow;
      this.dialogVisible = true;
    },
    // 查看考核指标表
    selectAssessIndexTable(row) {
      graduateStudentApi.queryAssessIndexTable(row.id).then(res => {
        this.dataListProp = res.data;
        this.tableFlag = true;
      });
    },
    // 取消
    cancel() {
      let allIsEmpty = true;
      for (let key in this.dialogForm) {
        if (this.dialogForm[key] || this.dialogForm[key] === 0) {
          allIsEmpty = false;
        }
      }
      // let diffFlag = false;
      // if (this.dialogMode === 'edit') {
      //   for (let editKey in this.editModeInfo) {
      //     for (let key in this.dialogForm) {
      //       if (editKey === key && this.editModeInfo[editKey] !== this.dialogForm[key]) {
      //         diffFlag = true;
      //       }
      //     }
      //   }
      // }
      if (allIsEmpty) {
        this.innerVisible = false;
        this.dialogVisible = false;
      } else {
        this.innerVisible = true;
      }
    },
    // 内层确认框-确认
    confirmInner() {
      this.innerVisible = false;
      this.dialogVisible = false;
    },
    // 内层确认框-取消
    cancelInner() {
      this.innerVisible = false;
    },
    // 内层确认框-保存并取消
    confirmAndClose(formName) {
      this.innerVisible = false;
      this.save(formName);
    },
    // 保存
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogMode === 'add') {
            if (this.dialogForm.hasOwnProperty('id')) {
              delete this.dialogForm.id;
            }
            if (this.dialogForm.hasOwnProperty('oldTemplateName')) {
              delete this.dialogForm.oldTemplateName;
            }
            graduateStudentApi.addAssessTemp(this.dialogForm).then(res => {
              this.$message({
                type: "success",
                message: this.$t('common.tips.addSuccess')
              });
              this.dialogVisible = false;
              this.onSubmit();
            });
          } else if (this.dialogMode === 'edit') {
            graduateStudentApi.editAssessTemp(this.dialogForm).then(res => {
              this.$message({
                type: "success",
                message: this.$t('common.tips.editSuccess')
              });
              this.dialogVisible = false;
              this.onSubmit();
            });
          }
        } else {
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error");
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus();
            }
          }, 1);
        }
      });
    },
    getListData() {
      graduateStudentApi.assessmentTempSetList(this.queryForm).then((res) => {
        this.dataList = res.data.list;
        this.queryForm.total_ = res.data.total_;
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 关闭x事件
    beforeClose: function (done) {
      if (this.dialogMode !== 'details') {
        this.cancel();
      } else {
        this.dialogVisible = false;
      }
    },
    // 关闭弹框
    closeDialog(formName) {
      this.dialogVisible = false;
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val;
      this.getListData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val;
      this.getListData();
    },
    reset() {
      this.baseLevel = [];
      Object.keys(this.queryForm.condition).forEach(key => this.queryForm.condition[key] = '');
      this.onSubmit();
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'graduateStu-tempSet-export') {
              this.permitToExport = true;
            }
            if (item.authCode === 'graduateStu-tempSet-add') {
              this.permitToAdd = true;
            }
            if (item.authCode === 'graduateStu-tempSet-edit') {
              this.permitToEdit = true;
            }
            if (item.authCode === 'graduateStu-tempSet-details') {
              this.permitToDetail = true;
            }
            if (item.authCode === 'graduateStu-tempSet-selectAssessIndex') {
              this.permitToSelectTable = true;
            }
          });
        }
      },
      deep: true,
      immediate: true
    },
    baseLevel: {
      handler(newVal) {
        if (newVal.length > 0) {
          this.queryForm.condition.baseLevel = newVal.join(',');
        } else {
          this.queryForm.condition.baseLevel = '';
        }
      },
      deep: true,
      immediate: true
    },
    dialogVisible: {
      handler(newVal) {
        if (!newVal) {
          if (this.$refs['dialogForm']) {
            this.$refs['dialogForm'].resetFields();
          }
          Object.keys(this.dialogForm).forEach(key => {
            this.$set(this.dialogForm, key, '');
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style lang="scss" scoped>
  .condition-title {
    color: #2b3b4e;
    font-size: 18px;
    line-height: 24px;
    font-weight: bold;
  }
  .edu-page-title {
    span {
      line-height: 24px;
      display: inline-block;
      padding-right: 10px;
      font-size: 18px;
      font-weight: bold;
      color: #2b3b4e;
    }
  }
  .sub-title {
    margin: 16px 0;
    font-size: 16px;
    color: #000020;
    letter-spacing: 0;
  }
  .template-setting-dialog ::v-deep {
    .el-select {
      width: 100%!important;
    }
  }
  .is-enabled-container ::v-deep {
    .el-button {
      cursor: auto;
    }
    .el-button--danger {
      padding: 9px 15px;
      min-width: 0;
    }
  }
  .template-setting-container ::v-deep {
    .el-dialog__body {
      word-break: break-all!important;
    }
  }
</style>
